package com.fyy.socket.udp.th;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * @Author fyy
 * @Description
 * @Date 2020/12/15 14:44
 */
public class AskThread extends Thread {

    private DatagramSocket socket;

    public AskThread(DatagramSocket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //接收数据
            byte[] buf = new byte[1024]; //接收数据包的大小
            int length = buf.length;
            DatagramPacket packet = new DatagramPacket(buf,length);
            socket.receive(packet);
            String msg = new String(packet.getData(),0,packet.getLength());
            System.out.println("客户端发送的数据：" + msg);
            //发送数据
            String s = "已收到消息";
            packet.setData(s.getBytes());
            packet.setLength(s.getBytes().length);
            packet.setAddress(packet.getAddress());
            packet.setPort(packet.getPort());
            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
